package com.winai.launcher.view.set;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.clj.fastble.BleManager;
import com.clj.fastble.callback.BleScanCallback;
import com.clj.fastble.data.BleDevice;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.ks.projectbasictools.utils.LogUtils;
import com.ks.projectbasictools.utils.ToastUtil;
import com.sdwfqin.cbt.CbtManager;
import com.sdwfqin.cbt.callback.ScanCallback;
import com.sdwfqin.cbt.callback.ServiceListenerCallback;
import com.winai.launcher.R;
import com.winai.launcher.adapter.BluetoothItemAdapter;
import com.winai.launcher.adapter.TitleAdapter;
import com.winai.launcher.base.BaseActivity;
import com.winai.launcher.bean.BluetoothItemBean;
import com.winai.launcher.bean.BluetoothItemBean.BluetoothState;
import com.winai.launcher.bean.BluetoothTitleBean;
import com.winai.launcher.common.GlobalPublisher;
import com.winai.launcher.common.SignalSlot;
import com.winai.launcher.constant.Constant;
import com.winai.launcher.interfaces.OnBluetoothOperationListener;
import com.winai.launcher.override.ToastKs;
import com.winai.launcher.override.dialog_global.GlobalDialog;
import com.winai.launcher.utils.BlueToothUtils;

import java.lang.ref.WeakReference;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 作者：康少
 * 时间：2019/11/19
 * 说明：设置蓝牙
 */
public class SetBluetoothActivity extends BaseActivity {
    private Context mContext = this;

    @BindView(R.id.list)
    LRecyclerView mRecyclerView;
    @BindView(R.id.str_title)
    TextView strTitle;
    @BindView(R.id.iv_refresh)
    ImageView ivRefresh;
    @BindView(R.id.cl_refresh)
    ConstraintLayout clRefresh;

    /*变量*/
    private LRecyclerViewAdapter mLRecyclerViewAdapter = null;
    @SuppressLint("StaticFieldLeak")
    private TitleAdapter titleAdapter;
    private BluetoothItemAdapter bindBluetoothItemAdapter;//已配对的蓝牙Adapter
    private BluetoothItemAdapter unbindBluetoothItemAdapter;//未配对的蓝牙Adapter

    protected boolean isUpdate = true;//定时刷新列表数据
    private final long TIME_TO_REFRESH = 30000;//设置定时刷新30秒
    private CountDownTimer countDownTimer;
    private boolean consume = false;

    //    private GlobalDialog.Builder timeoutDialog;
    private GlobalDialog.Builder connectFailDialog;
    private GlobalDialog.Builder bondDialog;
    private GlobalDialog.Builder createBondDialog;
    private Animation loadingAnimation;
    private MyBluetoothReceiver myBluetoothReceiver;
    private boolean isScanning = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_set_bluetooth);
        ButterKnife.bind(this);
        start();
    }

    private void start() {
        initObject();
        initListener();
        initView();
    }

    private void initObject() {
        String titleName = getIntent().getStringExtra("titleName");
        strTitle.setText(titleName);

        countDownTimer = new CountDownTimer(TIME_TO_REFRESH, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
            }

            @Override
            public void onFinish() {
                LogUtils.i("刷新Bluetooth列表倒计时结束，开始刷新");
                refreshBluetoothStatusOnTime();
            }
        };
        toggleBluetooth(true);
        mRecyclerView.setNestedScrollingEnabled(false);

        loadingAnimation = AnimationUtils.loadAnimation(mContext, R.anim.anim_loading);
        loadingAnimation.setInterpolator(new LinearInterpolator());

        bindBluetoothItemAdapter = new BluetoothItemAdapter(mContext, false, R.layout.item_wifi);
        unbindBluetoothItemAdapter = new BluetoothItemAdapter(mContext, true, R.layout.item_wifi);
        titleAdapter = new TitleAdapter(mContext, bindBluetoothItemAdapter, unbindBluetoothItemAdapter);

        mLRecyclerViewAdapter = new LRecyclerViewAdapter(titleAdapter);
        mRecyclerView.setAdapter(mLRecyclerViewAdapter);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        mRecyclerView.setPullRefreshEnabled(false);

        myBluetoothReceiver = new MyBluetoothReceiver(this);
        myBluetoothReceiver.register(mContext);
    }

    private void initListener() {
        GlobalPublisher.setListener(GlobalPublisher.ANY, new SignalSlot.Slot() {
            @Override
            public void onSignal(int what, int arg1, int agr2, Object argObj) {
                BluetoothDevice device = (BluetoothDevice) argObj;
                switch (what) {
                    case GlobalPublisher.REMOVE_BOND_BLUETOOTH://解除绑定蓝牙
                        // 1、将Item从我的设备移除 2、放到可用设备里面
                        updateItemFromMyDevice(false, device);
                        updateItemFromUseDevice(true, device);
                        notifyItemUI(device, BluetoothState.UNLINK);
                        break;
                    case GlobalPublisher.BLUETOOTH_STATE_ON://蓝牙打开
                        ToastUtil.show(mContext, "正在搜索蓝牙设备…");
                        titleAdapter.notifyItemChanged(0);
                        visibleScanAndLoading();
                        //开始扫描附近蓝牙设备
                        scanDevice();
                        break;
                    case GlobalPublisher.BLUETOOTH_STATE_OFF://蓝牙关闭
                        titleAdapter.notifyItemChanged(0);
                        goneScanAndLoading();
                        clearList();
                        break;
                }
            }
        });
        bindBluetoothItemAdapter.setOnBluetoothOperationListener(new OnBluetoothOperationListener() {
            @Override
            public void connect(BluetoothItemBean bean, TextView linkState, ImageView imageView) {
                SetBluetoothActivity.this.doConnect(bean, linkState, imageView);
            }

            @Override
            public void toggleBluetooth(boolean isOpen) {
                SetBluetoothActivity.this.toggleBluetooth(isOpen);
            }
        });
        unbindBluetoothItemAdapter.setOnBluetoothOperationListener(new OnBluetoothOperationListener() {
            @Override
            public void connect(BluetoothItemBean bean, TextView linkState, ImageView imageView) {
                SetBluetoothActivity.this.doConnect(bean, linkState, imageView);
            }

            @Override
            public void toggleBluetooth(boolean isOpen) {
                SetBluetoothActivity.this.toggleBluetooth(isOpen);
            }
        });
    }

    /**
     * 说明：提示配对失败弹窗
     *
     * @param device
     */
    private void showFailDialog(BluetoothDevice device) {
        // 弹窗提示，确保优先关闭已弹窗的界面
        if (bondDialog != null && bondDialog.create().isShowing()) {
            bondDialog.create().dismiss();
        }
        if (createBondDialog != null && createBondDialog.create().isShowing()) {
            createBondDialog.create().dismiss();
        }
        if (!SetBluetoothActivity.this.isFinishing()) {
            if (connectFailDialog == null) {
                connectFailDialog = new GlobalDialog.Builder(mContext)
                        .setTitle("连接不成功")
                        .setCancelText("好")
                        .setCancelGradient(false);
            }
            connectFailDialog.setContent("请确定“" + device.getName() + "”已打开而且在可用范围内。").show();
        } else {
            LogUtils.e("蓝牙连接页面已关闭，无需再弹出连接失败弹窗了");
        }
    }

    /**
     * 说明：通知更新item的UI
     */
    private synchronized void notifyItemUI(BluetoothDevice device, BluetoothState mBluetoothState) {
        LogUtils.v("通知更新蓝牙" + device.getName() + "的UI：mBluetoothState = " + mBluetoothState);
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                if (isBindDevice(device)) {
                    for (int position = 0; position < bindBluetoothItemAdapter.getData().size(); position++) {
                        if (bindBluetoothItemAdapter.getData().get(position).getDevice().getMac().equals(device.getAddress())) {
                            bindBluetoothItemAdapter.getData().get(position).setBluetoothState(mBluetoothState);
                            bindBluetoothItemAdapter.notifyDataSetChanged();
                            break;
                        }
                    }
                } else {
                    for (int position = 0; position < unbindBluetoothItemAdapter.getData().size(); position++) {
                        if (unbindBluetoothItemAdapter.getData().get(position).getDevice().getMac().equals(device.getAddress())) {
                            //配对没有成功
                            unbindBluetoothItemAdapter.getData().get(position).setBluetoothState(mBluetoothState);
                            unbindBluetoothItemAdapter.notifyDataSetChanged();
                            break;
                        }
                    }
                }
                //置顶
                if (mBluetoothState == BluetoothState.BONDED || mBluetoothState == BluetoothState.LINKED) {
                    bindBluetoothItemAdapter.onTop(device);
                    mRecyclerView.scrollToPosition(0);
                }
            }
        });
    }

    /**
     * 说明：设置设备蓝牙永久可被发现
     */
    public void setDiscoverableTimeout(int timeout) {
        BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
        try {
            Method setDiscoverableTimeout = BluetoothAdapter.class.getMethod("setDiscoverableTimeout", int.class);
            setDiscoverableTimeout.setAccessible(true);
            Method setScanMode = BluetoothAdapter.class.getMethod("setScanMode", int.class, int.class);
            setScanMode.setAccessible(true);
            setDiscoverableTimeout.invoke(adapter, timeout);
            setScanMode.invoke(adapter, BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE, timeout);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void closeDiscoverableTimeout() {
        setDiscoverableTimeout(1);
    }

    /**
     * 说明：从“我的设备”中添加或移除
     */
    private void updateItemFromMyDevice(boolean isInsert, BluetoothDevice device) {
        if (isInsert) {
            if (!deviceExistInBind(device.getName())) {
                bindBluetoothItemAdapter.getData().add(0, new BluetoothItemBean(0
                        , device.getName(), BluetoothState.UNLINK, new BleDevice(device)));
                bindBluetoothItemAdapter.notifyItemInserted(0);
            }
        } else {
            for (int i = 0; i < bindBluetoothItemAdapter.getData().size(); i++) {
                if (bindBluetoothItemAdapter.getData().get(i).getBluetoothName().equals(device.getName())) {
                    bindBluetoothItemAdapter.getData().remove(i);
                    //推荐用这个
                    bindBluetoothItemAdapter.notifyItemRemoved(i);
                    // 如果移除的是最后一个，忽略 注意：这里的mDataAdapter.getDataList()不需要-1，因为上面已经-1了
//                    if (i != (bindBluetoothItemAdapter.getData().size())) {
                    bindBluetoothItemAdapter.notifyItemRangeChanged(i
                            , bindBluetoothItemAdapter.getData().size() - i);
//                    }
                    break;
                }
            }
        }
        refreshTitle();
    }

    /**
     * 说明：从“可用设备”中添加或移除
     */
    private void updateItemFromUseDevice(boolean isInsert, BluetoothDevice device) {
        if (isInsert) {
            if (!deviceExistInUnbind(device.getName())) {
                unbindBluetoothItemAdapter.getData().add(0, new BluetoothItemBean(0
                        , device.getName(), BluetoothState.UNLINK, new BleDevice(device)));
                unbindBluetoothItemAdapter.notifyItemInserted(0);
            }
        } else {
            for (int i = 0; i < unbindBluetoothItemAdapter.getData().size(); i++) {
                if (unbindBluetoothItemAdapter.getData().get(i).getBluetoothName().equals(device.getName())) {
                    unbindBluetoothItemAdapter.getData().remove(i);
                    //推荐用这个
                    unbindBluetoothItemAdapter.notifyItemRemoved(i);
                    // 如果移除的是最后一个，忽略 注意：这里的mDataAdapter.getDataList()不需要-1，因为上面已经-1了
//                    if (i != (unbindBluetoothItemAdapter.getData().size())) {
                    unbindBluetoothItemAdapter.notifyItemRangeChanged(i
                            , unbindBluetoothItemAdapter.getData().size() - i);
//                    }
                    break;
                }
            }
        }
    }

    /**
     * Desc 添加数据
     */
    private void initView() {
        titleAdapter.getData().add(new BluetoothTitleBean(-1, "蓝牙配对"
                , BleManager.getInstance().getBluetoothAdapter().getName()));
        titleAdapter.notifyItemInserted(0);

        List<BluetoothDevice> bondedDevices = BlueToothUtils.getInstance().getBondedDevices();
        for (BluetoothDevice bd : bondedDevices) {
            inputBindList(bd);
        }
        scanDevice();
    }

    /**
     * 说明：扫描附近蓝牙设备
     */
    private void scanDevice() {
        //扫描Le设备
        BleManager.getInstance().scan(new BleScanCallback() {
            @Override
            public void onScanStarted(boolean success) {
                LogUtils.i("BLE==>   开始扫描");
            }

            @Override
            public void onScanning(BleDevice bleDevice) {
//                BluetoothDevice device = bleDevice.getDevice();
//                if (isBindDevice(device)) {
//                    inputBindList(device);
//                } else {
//                    inputUnbindList(device);
//                }
                if (!TextUtils.isEmpty(bleDevice.getName()))
                    LogUtils.i("BLE==>   扫描到设备:蓝牙名称：" + bleDevice.getName() + "，物理地址：" + bleDevice.getMac());
            }

            @Override
            public void onScanFinished(List<BleDevice> scanResultList) {
                LogUtils.i("BLE==>   搜索完成");
            }
        });
        //扫描经典设备
        CbtManager.getInstance()
                .scan(new ScanCallback() {
                    @Override
                    public void onScanStart(boolean isOn) {
                        LogUtils.i("BT==>   开始扫描");
                    }

                    @Override
                    public void onScanStop(List<BluetoothDevice> devices) {
                        LogUtils.i("BT==>   扫描完成");
                    }

                    @Override
                    public void onFindDevice(BluetoothDevice device) {
//                        if (isBindDevice(device)) {
//                            inputBindList(device);
//                        } else {
//                            inputUnbindList(device);
//                        }
                        if (!TextUtils.isEmpty(device.getName()))
                            LogUtils.i("BT==>   扫描到设备:蓝牙名称：" + device.getName() + "，物理地址：" + device.getAddress());
                    }
                });
    }

    /**
     * 说明：是否属于“我的设备”范畴
     */
    private boolean isBindDevice(BluetoothDevice device) {
        List<BluetoothDevice> bondedDevices = BlueToothUtils.getInstance().getBondedDevices();
        for (BluetoothDevice bd : bondedDevices) {
            if (bd.getAddress().equals(device.getAddress())) {
                return true;
            }
        }
        return false;
    }

    /**
     * 说明：添加到可用设备列表
     */
    private void inputUnbindList(BluetoothDevice device) {
        if (unbindBluetoothItemAdapter != null) {
            if (!TextUtils.isEmpty(device.getName()) && !deviceExistInUnbind(device.getName())) {
                List<BluetoothItemBean> unBList = new ArrayList<>();
                BluetoothState mBluetoothState = BluetoothState.UNLINK;
                if (Constant.operationDevice != null
                        && device.getAddress().equals(Constant.operationDevice.getAddress())
                        && Constant.bluetoothLinked) {
                    mBluetoothState = BluetoothState.LINKED;
                }
                unBList.add(new BluetoothItemBean(0, device.getName(), mBluetoothState
                        , new BleDevice(device)));
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        unbindBluetoothItemAdapter.addDataList(unBList);//加载未绑定列表
                    }
                });
            }
        }
    }

    /**
     * 说明：添加到我的设备列表
     */
    private void inputBindList(BluetoothDevice device) {
        if (bindBluetoothItemAdapter != null) {
            if (!TextUtils.isEmpty(device.getName()) && !deviceExistInBind(device.getName())) {
                List<BluetoothItemBean> bList = new ArrayList<>();
                BluetoothState mBluetoothState = BluetoothState.UNLINK;
                if (Constant.operationDevice != null
                        && device.getAddress().equals(Constant.operationDevice.getAddress())
                        && Constant.bluetoothLinked) {
                    mBluetoothState = BluetoothState.LINKED;
                }
                bList.add(new BluetoothItemBean(0, device.getName(), mBluetoothState
                        , new BleDevice(device)));
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        bindBluetoothItemAdapter.addDataList(bList);//加载已绑定列表
                    }
                });
            }
            if (Constant.operationDevice != null && Constant.bluetoothLinked) {
                bindBluetoothItemAdapter.onTop(Constant.operationDevice);
                mRecyclerView.scrollToPosition(0);
            }
        }
        refreshTitle();
    }

    /**
     * 定时刷新Wifi列表信息
     */
    private void refreshBluetoothStatusOnTime() {
        if (isUpdate) {
            //开始扫描附近蓝牙设备
            scanDevice();
        }
    }

    /**
     * 说明：刷新我的设备 和 可用设备
     */
    private void refreshTitle() {
        //添加Title标题栏——我的设备
        List<BluetoothDevice> bondedDevices = BlueToothUtils.getInstance().getBondedDevices();
        if (((bondedDevices.size() > 0)) && titleAdapter.getData().size() < 3) {
            titleAdapter.getData().add(1, new BluetoothTitleBean(-2, "我的设备"));
            titleAdapter.notifyItemInserted(1);
        } else if ((bondedDevices.size() == 0 && titleAdapter.getData().size() > 2)) {
            titleAdapter.getData().remove(1);
            //推荐用这个
            titleAdapter.notifyItemRemoved(1);
//            titleAdapter.notifyItemRangeChanged(1
//                    , titleAdapter.getData().size() - 1);
        }
        //添加Title标题栏——可用设备
        if (!unBondExit()) {
            titleAdapter.getData().add(new BluetoothTitleBean(-3, "可用设备"));
            titleAdapter.notifyItemInserted(2);
        }
        //刷新视图
//        new Handler(Looper.getMainLooper()).post(new Runnable() {
//            @Override
//            public void run() {
//                titleAdapter.refreshData(bluetoothTitleBeanList);
//                mRecyclerView.refreshComplete(bluetoothTitleBeanList.size());
//            }
//        });
    }

    /**
     * 说明：是否已存在标题“可用设备”
     */
    private boolean unBondExit() {
        for (int i = 0; i < titleAdapter.getData().size(); i++) {
            if (titleAdapter.getData().get(i).getTitleId() == -3) {
                return true;
            }
        }
        return false;
    }

    public void showProgressBar() {
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                ivRefresh.startAnimation(loadingAnimation);
            }
        });
    }

    public void hidingProgressBar() {
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                ivRefresh.clearAnimation();
            }
        });
    }

    private void goneScanAndLoading() {
        clRefresh.setVisibility(View.GONE);
    }

    private void visibleScanAndLoading() {
        clRefresh.setVisibility(View.VISIBLE);
    }


    /**
     * 说明：执行连接操作
     */
    private void doConnect(BluetoothItemBean bean, TextView linkState, ImageView imageView) {
        //停止扫描搜索
        CbtManager.getInstance().onScanStop();
        BleManager.getInstance().cancelScan();
        //开启连接或配对
        if (bean.getDevice().getDevice().getType() == BluetoothDevice.DEVICE_TYPE_CLASSIC
                || bean.getDevice().getDevice().getType() == BluetoothDevice.DEVICE_TYPE_DUAL) {
            //经典蓝牙 或 双模式
            if (bean.getDevice().getDevice().getBondState() == BluetoothDevice.BOND_BONDED) {
                //已配对
//                connectByBt(bean, linkState, imageView);
//                notifyItemUI(bean.getDevice().getDevice(), BluetoothState.LINKING);
                if (bondDialog == null) {
                    bondDialog = new GlobalDialog.Builder(mContext)
                            .setContent("已配对，请在手机上进行连接操作")
                            .setCancelText("好")
                            .setCancelGradient(true);
                }
                bondDialog.show();
            } else {
                //未配对
                bean.getDevice().getDevice().createBond();
                notifyItemUI(bean.getDevice().getDevice(), BluetoothState.BONDING);
                if (createBondDialog == null) {
                    createBondDialog = new GlobalDialog.Builder(mContext)
                            .setContent("已向设备发出配对申请，请在设备上执行配对操作")
                            .setCancelText("好")
                            .setCancelGradient(true);
                }
                createBondDialog.show();
            }
        } else if (bean.getDevice().getDevice().getType() == BluetoothDevice.DEVICE_TYPE_LE) {
            //低功耗
            ToastKs.show(mContext, "请使用此设备对应的应用完成配对");
        }
    }

    /**
     * Desc 切换蓝牙开关
     */
    private void toggleBluetooth(boolean isOpen) {
        if (isOpen) {
            BleManager.getInstance().enableBluetooth();
            setDiscoverableTimeout(300);
            //开启蓝牙服务端
            CbtManager.getInstance().startServiceListener(new ServiceListenerCallback() {
                @Override
                public void onStartError(Throwable throwable) {
                    LogUtils.e("启动蓝牙服务失败，errMsg = " + throwable.getMessage());
                }

                @Override
                public void onDataListener(String s, BluetoothDevice device) {
                    LogUtils.i("启动蓝牙服务成功，s = " + s + ";deviceName = " + device.getName() + ";deviceAddress = " + device.getAddress());
                }
            });
        } else {
            BleManager.getInstance().disableBluetooth();
            try {
                /*关闭服务*/
                CbtManager.getInstance().closeService();
                CbtManager.getInstance().onDestroy();
                /*停止扫描*/
                BleManager.getInstance().cancelScan();
                CbtManager.getInstance().onScanStop();
            } catch (Exception e) {
                e.printStackTrace();
            }
            closeDiscoverableTimeout();
        }
    }

    /**
     * Desc 关闭蓝牙清空数据
     */
    private void clearList() {
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                titleAdapter.refreshData(null);
                mRecyclerView.refreshComplete(0);
                titleAdapter.getData().add(new BluetoothTitleBean(-1, "蓝牙配对"
                        , BleManager.getInstance().getBluetoothAdapter().getName()));
                titleAdapter.notifyItemInserted(0);
            }
        });
    }

    /**
     * 说明：判断发现的设备是否已添加到可用设备
     */
    private boolean deviceExistInUnbind(String deviceName) {
        List<BluetoothItemBean> dataList = unbindBluetoothItemAdapter.getData();
        for (BluetoothItemBean bean : dataList) {
            if (bean.getBluetoothName().equals(deviceName)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 说明：判断发现的设备是否已添加到我的设备
     */
    private boolean deviceExistInBind(String deviceName) {
        if (bindBluetoothItemAdapter == null) {
            return false;
        }
        List<BluetoothItemBean> dataList = bindBluetoothItemAdapter.getData();
        for (BluetoothItemBean bean : dataList) {
            if (bean.getBluetoothName().equals(deviceName)) {
                return true;
            }
        }
        return false;
    }

    private static class MyBluetoothReceiver extends BroadcastReceiver {
        WeakReference<SetBluetoothActivity> weakReference;

        public MyBluetoothReceiver(SetBluetoothActivity activity) {
            weakReference = new WeakReference<>(activity);
        }

        public void register(Context mContext) {
            /**
             * 异步搜索蓝牙设备——广播接收
             */
            IntentFilter filter = new IntentFilter();
            filter.addAction(Constant.ACTION_BLUETOOTH_SCAN_START);//开始扫描
            filter.addAction(Constant.ACTION_BLUETOOTH_SCAN_COMPLETE);//扫描完成
            filter.addAction(Constant.ACTION_BLUETOOTH_FIND_ONE);//扫描到设备
            filter.addAction(Constant.ACTION_BLUETOOTH_BOND_STATE_CHANGED);//绑定状态改变
            filter.addAction(Constant.ACTION_BLUETOOTH_DEVICE_CONNECTED);//设备连接成功
            filter.addAction(Constant.ACTION_BLUETOOTH_DEVICE_CONNECTING);//设备正在连接
            filter.addAction(Constant.ACTION_BLUETOOTH_DEVICE_DISCONNECTED);//设备断开连接
            // 注册广播
            mContext.getApplicationContext().registerReceiver(this, filter);
        }

        @Override
        public void onReceive(Context context, Intent intent) {
            BluetoothDevice device = intent.getParcelableExtra("device");
            String action = intent.getAction();
            if (action == null) {
                return;
            }
            switch (action) {
                case Constant.ACTION_BLUETOOTH_SCAN_START:
                    if (weakReference.get() != null) {
                        weakReference.get().showProgressBar();
                        weakReference.get().refreshTitle();
                        weakReference.get().setScanning(true);
                    }
                    break;
                case Constant.ACTION_BLUETOOTH_SCAN_COMPLETE:
                    if (weakReference.get() != null) {
                        weakReference.get().hidingProgressBar();
                        weakReference.get().setScanning(false);
                    }
                    break;
                case Constant.ACTION_BLUETOOTH_FIND_ONE:
                    if (weakReference.get() != null) {
                        // 判断是否配对过
                        if (weakReference.get().isBindDevice(device)) {
                            weakReference.get().inputBindList(device);
                        } else {
                            weakReference.get().inputUnbindList(device);
                        }
                    }
                    break;
                case Constant.ACTION_BLUETOOTH_BOND_STATE_CHANGED:
                    if (weakReference.get() != null && device != null) {
                        int bondState = device.getBondState();
                        if (bondState == BluetoothDevice.BOND_NONE) {
                            //取消配对、未配对
                            weakReference.get().updateItemFromMyDevice(false, device);
                            weakReference.get().updateItemFromUseDevice(true, device);
                            weakReference.get().notifyItemUI(device, BluetoothState.UNBOND);
                            // 弹窗提示配对失败
                            weakReference.get().showFailDialog(device);
                        } else if (bondState == BluetoothDevice.BOND_BONDING) {
                            //配对中
                            weakReference.get().notifyItemUI(device, BluetoothState.BONDING);
                        } else if (bondState == BluetoothDevice.BOND_BONDED) {
                            //配对成功
                            weakReference.get().updateItemFromMyDevice(true, device);
                            weakReference.get().updateItemFromUseDevice(false, device);
                            weakReference.get().notifyItemUI(device, BluetoothState.BONDED);
                        }
                    }
                    break;
                case Constant.ACTION_BLUETOOTH_DEVICE_CONNECTED:
                    if (weakReference.get() != null && device != null) {
                        weakReference.get().updateItemFromMyDevice(true, device);
                        weakReference.get().updateItemFromUseDevice(false, device);
                        weakReference.get().notifyItemUI(device, BluetoothState.LINKED);
                    }
                    GlobalPublisher.Notify(GlobalPublisher.BOND_BLUETOOTH);
                    break;
                case Constant.ACTION_BLUETOOTH_DEVICE_CONNECTING:
                    if (weakReference.get() != null && device != null) {
                        weakReference.get().notifyItemUI(device, BluetoothState.LINKING);
                    }
                    break;
                case Constant.ACTION_BLUETOOTH_DEVICE_DISCONNECTED:
                    CbtManager.getInstance().disableCancelService();
                    if (weakReference.get() != null && device != null) {
                        weakReference.get().notifyItemUI(device, BluetoothState.UNLINK);
                        GlobalPublisher.Notify(GlobalPublisher.BLUETOOTH_DEVICE_DISCONNECTED);
                    }
                    break;
            }
        }
    }

    private void setScanning(boolean isScanning) {
        this.isScanning = isScanning;
    }

    @OnClick({R.id.iv_back, R.id.iv_home, R.id.cl_refresh})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_home:
                //模拟HOME
                Intent it = new Intent(Intent.ACTION_MAIN);
                it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                it.addCategory(Intent.CATEGORY_HOME);
                mContext.startActivity(it);
                break;
            case R.id.cl_refresh:
                if (isScanning) {
                    ToastKs.show(mContext, "正在扫描…");
                    return;
                }
                if (countDownTimer != null) {
                    countDownTimer.cancel();
                }
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        unbindBluetoothItemAdapter.refreshData(null);
                    }
                });
                //开始扫描附近蓝牙设备
                scanDevice();
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        isUpdate = true;
    }

    @Override
    protected void onPause() {
        super.onPause();
        isUpdate = false;
        consume = true;
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        CbtManager.getInstance().onScanStop();
//        BleManager.getInstance().cancelScan();
        isUpdate = false;
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
        try {
            if (myBluetoothReceiver != null) {
                unregisterReceiver(myBluetoothReceiver);
            }
        } catch (IllegalArgumentException e) {
            //LogUtils.e("捕捉一个crash：Receiver not registered: mScreenOffReceiver");
        }
    }
}
